﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Globalization;
using System.Configuration;
using System.Text.RegularExpressions;
using System.Web.UI.WebControls;
using System.Data;
using System.Net;
using System.Net.Mail;
using System.Security.Cryptography;
using System.IO;
using System.Runtime.InteropServices;
using System.Web;
using System.Drawing.Imaging;
using System.Collections;

namespace BLL
{
  [Serializable, StructLayout(LayoutKind.Sequential)]
    public struct MyDate : IComparable
    {
        private ushort _day;
        private ushort _month;
        private ushort _year;
        public ushort Day
        {
            get
            {
                return this._day;
            }
            set
            {
                if (value > 0x1f)
                {
                    throw new ArgumentException("Day out of range[31]");
                }
                this._day = value;
            }
        }
        public ushort Month
        {
            get
            {
                return this._month;
            }
            set
            {
                if (value > 12)
                {
                    throw new ArgumentException("Month out of range[12]");
                }
                this._month = value;
            }
        }
        public ushort Year
        {
            get
            {
                return this._year;
            }
            set
            {
                if (value.ToString().Length > 4)
                {
                    throw new ArgumentException("Year out of range.");
                }
                this._year = value;
            }
        }
        public MyDate(DateTime dt)
        {
            this._month = Convert.ToUInt16(dt.Month);
            this._day = Convert.ToUInt16(dt.Day);
            this._year = Convert.ToUInt16(dt.Year);
        }

        public MyDate(string dt)
        {
            this._day = Convert.ToUInt16(dt.Split(new char[] { '/' })[0]);
            this._month = Convert.ToUInt16(dt.Split(new char[] { '/' })[1]);
            this._year = Convert.ToUInt16(dt.Split(new char[] { '/' })[2]);
        }

        public bool IsDateTime(string dt)
        {
            Regex rgx = new Regex(@"(?\d{1,2})/(?\d{1,2})/(?(?:\d{4}|\d{2}))");
            return rgx.IsMatch(dt);
        }

        public DateTime StringToDate(string dt)
        {
            if (!this.IsDateTime(dt))
            {
                throw new ArgumentException("The string can't be converted to a date");
            }
            this._day = Convert.ToUInt16(dt.Split(new char[] { '/' })[0]);
            this._month = Convert.ToUInt16(dt.Split(new char[] { '/' })[1]);
            this._year = Convert.ToUInt16(dt.Split(new char[] { '/' })[2]);
            return new DateTime(this.Year, this.Month, this.Day);
        }

        public DateTime ToDateTime()
        {
            return new DateTime(this.Year, this.Month, this.Day);
        }

        public static DateTime ToDateTime(MyDate dt)
        {
            return new DateTime(dt.Year, dt.Month, dt.Day);
        }

        public int CompareTo(object obj)
        {
            MyDate dt = (MyDate)obj;
            ushort i = 0;
            if (dt._day == this._day)
            {
                i = (ushort)(i + 100);
            }
            if (dt._month == this._month)
            {
                i = (ushort)(i + 10);
            }
            if (dt._year == this._year)
            {
                i = (ushort)(i + 1);
            }
            return i;
        }

        public override bool Equals(object obj)
        {
            MyDate dt = (MyDate)obj;
            return (((dt._day == this._day) && (dt._month == this._month)) && (dt._year == this._year));
        }

        public override int GetHashCode()
        {
            return ((this._day ^ this._month) ^ this._year);
        }

        public override string ToString()
        {
            return (this._day.ToString() + "/" + this._month.ToString() + "/" + this._year.ToString());
        }

    }
    public class ProcessControl
    {
        public static void AddScriptHighLightOnDataGrid(ref DataGrid dg)
        {
            try
            {
                if (dg.Items.Count > 0)
                {
                    for (int i = 0; i < dg.Items.Count; i++)
                    {
                        string RowID = dg.Items[i].ClientID;
                        dg.Items[i].Attributes.Add("onMouseMove", "Javascript:SelectRowOnGrid_OnMouseMove(" + RowID + ")");
                        dg.Items[i].Attributes.Add("onMouseOut", "Javascript:SelectRowOnGrid_OnMouseOut(" + RowID + ")");
                    }
                }
            }
            catch
            {
            }
        }

        public static void AddScriptHighLightOnGridView(ref GridView gv)
        {
            try
            {
                if (gv.Rows.Count > 0)
                {
                    for (int i = 0; i < gv.Rows.Count; i++)
                    {
                        gv.Rows[i].Attributes.Add("onmouseover", "javascript:this.originalstyle=this.style.backgroundColor;this.style.backgroundColor='#cae0ff'");
                        gv.Rows[i].Attributes.Add("onmouseout", "javascript:this.style.backgroundColor=this.originalstyle;");
                    }
                }
            }
            catch
            {
            }
        }

        public static void EnabledButton(Button[] btEnable, Button[] btNotEnable)
        {
            try
            {
                foreach (Button i in btEnable)
                {
                    i.Enabled = true;
                }
                foreach (Button j in btNotEnable)
                {
                    j.Enabled = false;
                }
            }
            catch
            {
            }
        }

        public static void EnabledButton(Button[] bt, bool show)
        {
            try
            {
                foreach (Button i in bt)
                {
                    i.Enabled = show;
                }
            }
            catch
            {
            }
        }

        public static void EnableTextBox(TextBox[] txt, bool show)
        {
            foreach (TextBox t in txt)
            {
                t.Enabled = show;
            }
        }

        public static void FillDataInDropDownList(ref DropDownList ddl, DataTable tb, string ID, string Ten)
        {
            try
            {
                if (tb.Rows.Count > 0)
                {
                    for (int i = 0; i < tb.Rows.Count; i++)
                    {
                        ddl.Items.Add(new ListItem(tb.Rows[i][Ten].ToString(), tb.Rows[i][ID].ToString()));
                    }
                }
            }
            catch
            {
            }
        }

        public static void FormatNumberInGrid(ref DataGrid dg, int chisocot, int dinhdang)
        {
            try
            {
                int i;
                if (dinhdang == 1)
                {
                    if (dg.Items.Count > 0)
                    {
                        for (i = 0; i < dg.Items.Count; i++)
                        {
                            if (dg.Items[i].Cells[chisocot].Text == "")
                            {
                                dg.Items[i].Cells[chisocot].Text = "0";
                            }
                            else
                            {
                                dg.Items[i].Cells[chisocot].Text = XuLySo.FormatSo_KhongThapPhan(dg.Items[i].Cells[chisocot].Text.ToString());
                            }
                        }
                    }
                }
                else if (dinhdang == 2)
                {
                    if (dg.Items.Count > 0)
                    {
                        for (i = 0; i < dg.Items.Count; i++)
                        {
                            if (dg.Items[i].Cells[chisocot].Text == "")
                            {
                                dg.Items[i].Cells[chisocot].Text = "0";
                            }
                            else
                            {
                                dg.Items[i].Cells[chisocot].Text = XuLySo.FormatSo_CoThapPhan(dg.Items[i].Cells[chisocot].Text.ToString());
                            }
                        }
                    }
                }
                else if (dinhdang == 3)
                {
                    if (dg.Items.Count > 0)
                    {
                        for (i = 0; i < dg.Items.Count; i++)
                        {
                            if (dg.Items[i].Cells[chisocot].Text == "")
                            {
                                dg.Items[i].Cells[chisocot].Text = "0";
                            }
                            else
                            {
                                dg.Items[i].Cells[chisocot].Text = XuLySo.FormatTien_VND(dg.Items[i].Cells[chisocot].Text.ToString());
                            }
                        }
                    }
                }
                else if (dinhdang == 4)
                {
                    if (dg.Items.Count > 0)
                    {
                        for (i = 0; i < dg.Items.Count; i++)
                        {
                            if (dg.Items[i].Cells[chisocot].Text == "")
                            {
                                dg.Items[i].Cells[chisocot].Text = "0";
                            }
                            else
                            {
                                dg.Items[i].Cells[chisocot].Text = XuLySo.FormatTien_USD(dg.Items[i].Cells[chisocot].Text.ToString());
                            }
                        }
                    }
                }
                else if (dg.Items.Count > 0)
                {
                    for (i = 0; i < dg.Items.Count; i++)
                    {
                        if (dg.Items[i].Cells[chisocot].Text == "")
                        {
                            dg.Items[i].Cells[chisocot].Text = "0";
                        }
                        else
                        {
                            dg.Items[i].Cells[chisocot].Text = XuLySo.FormatSo_KhongThapPhan(dg.Items[i].Cells[chisocot].Text.ToString());
                        }
                    }
                }
            }
            catch
            {
            }
        }

        public static void FormatNumberInGridView(ref GridView gv, int chisocot, int dinhdang)
        {
            try
            {
                int i;
                if (dinhdang == 1)
                {
                    if (gv.Rows.Count > 0)
                    {
                        for (i = 0; i < gv.Rows.Count; i++)
                        {
                            if (gv.Rows[i].Cells[chisocot].Text == "")
                            {
                                gv.Rows[i].Cells[chisocot].Text = "0";
                            }
                            else
                            {
                                gv.Rows[i].Cells[chisocot].Text = XuLySo.FormatSo_KhongThapPhan(gv.Rows[i].Cells[chisocot].Text.ToString());
                            }
                        }
                    }
                }
                else if (dinhdang == 2)
                {
                    if (gv.Rows.Count > 0)
                    {
                        for (i = 0; i < gv.Rows.Count; i++)
                        {
                            if (gv.Rows[i].Cells[chisocot].Text == "")
                            {
                                gv.Rows[i].Cells[chisocot].Text = "0";
                            }
                            else
                            {
                                gv.Rows[i].Cells[chisocot].Text = XuLySo.FormatSo_CoThapPhan(gv.Rows[i].Cells[chisocot].Text.ToString());
                            }
                        }
                    }
                }
                else if (dinhdang == 3)
                {
                    if (gv.Rows.Count > 0)
                    {
                        for (i = 0; i < gv.Rows.Count; i++)
                        {
                            if (gv.Rows[i].Cells[chisocot].Text == "")
                            {
                                gv.Rows[i].Cells[chisocot].Text = "0";
                            }
                            else
                            {
                                gv.Rows[i].Cells[chisocot].Text = XuLySo.FormatTien_VND(gv.Rows[i].Cells[chisocot].Text.ToString());
                            }
                        }
                    }
                }
                else if (dinhdang == 4)
                {
                    if (gv.Rows.Count > 0)
                    {
                        for (i = 0; i < gv.Rows.Count; i++)
                        {
                            if (gv.Rows[i].Cells[chisocot].Text == "")
                            {
                                gv.Rows[i].Cells[chisocot].Text = "0";
                            }
                            else
                            {
                                gv.Rows[i].Cells[chisocot].Text = XuLySo.FormatTien_USD(gv.Rows[i].Cells[chisocot].Text.ToString());
                            }
                        }
                    }
                }
                else if (gv.Rows.Count > 0)
                {
                    for (i = 0; i < gv.Rows.Count; i++)
                    {
                        if (gv.Rows[i].Cells[chisocot].Text == "")
                        {
                            gv.Rows[i].Cells[chisocot].Text = "0";
                        }
                        else
                        {
                            gv.Rows[i].Cells[chisocot].Text = XuLySo.FormatSo_KhongThapPhan(gv.Rows[i].Cells[chisocot].Text.ToString());
                        }
                    }
                }
            }
            catch
            {
            }
        }

        public static int GetIndexDropDownList(DropDownList ddl, string strFind)
        {
            int rval = 0;
            try
            {
                for (int i = 0; i <= (ddl.Items.Count - 1); i++)
                {
                    if (ddl.Items[i].Value == strFind)
                    {
                        return i;
                    }
                }
            }
            catch
            {
                rval = 0;
            }
            return rval;
        }

        private void SortDropDownList(ref DropDownList objDDL)
        {
            ArrayList textList = new ArrayList();
            ArrayList valueList = new ArrayList();
            foreach (ListItem li in objDDL.Items)
            {
                textList.Add(li.Text);
            }
            textList.Sort();
            foreach (object item in textList)
            {
                string value = objDDL.Items.FindByText(item.ToString()).Value;
                valueList.Add(value);
            }
            objDDL.Items.Clear();
            for (int i = 0; i < textList.Count; i++)
            {
                ListItem objItem = new ListItem(textList[i].ToString(), valueList[i].ToString());
                objDDL.Items.Add(objItem);
            }
        }

        public static string StrGetAllItemInGridView(GridView gv, string chkid, string idcontrl)
        {
            string strReturn = "";
            try
            {
                foreach (GridViewRow row in gv.Rows)
                {
                    Label lbl = (Label)row.FindControl(idcontrl);
                    if (lbl != null)
                    {
                        strReturn = (strReturn == "") ? lbl.Text.Trim() : (strReturn + "," + lbl.Text.Trim());
                    }
                }
            }
            catch
            {
                strReturn = "";
            }
            return strReturn;
        }

        public static string StrReturnGridView(GridView gv, string chkid, string idcontrl)
        {
            string strReturn = "";
            try
            {
                foreach (GridViewRow row in gv.Rows)
                {
                    CheckBox chk = (CheckBox)row.FindControl(chkid);
                    if (chk.Checked)
                    {
                        Label lbl = (Label)row.FindControl(idcontrl);
                        if (lbl != null)
                        {
                            strReturn = (strReturn == "") ? lbl.Text.Trim() : (strReturn + "," + lbl.Text.Trim());
                        }
                    }
                }
            }
            catch
            {
                strReturn = "";
            }
            return strReturn;
        }

        public static double SumColumInDataGrid(DataGrid dtg, int chisocot)
        {
            double Tong = 0.0;
            try
            {
                for (int i = 0; i < dtg.Items.Count; i++)
                {
                    Tong += double.Parse(XuLySo.HuyFormat(dtg.Items[i].Cells[chisocot].Text.ToString()));
                }
            }
            catch
            {
            }
            return Tong;
        }

        public static double SumColumInGridView(GridView gv, int chisocot)
        {
            double Tong = 0.0;
            try
            {
                for (int i = 0; i < gv.Rows.Count; i++)
                {
                    Tong += double.Parse(XuLySo.HuyFormat(gv.Rows[i].Cells[chisocot].Text.ToString()));
                }
            }
            catch
            {
            }
            return Tong;
        }
    }
    public class XuLySo
    {
        // Fields
        private static CultureInfo _CULTURE = new CultureInfo(ConfigurationSettings.AppSettings["culture"]);
        private static string _DAU_CACH_THAP_PHAN = _CULTURE.NumberFormat.NumberDecimalSeparator;
        private static string _DAU_PHAN_NHOM = _CULTURE.NumberFormat.NumberGroupSeparator;
        private static string _SO_LUONG_THAP_PHAN_SO = ConfigurationSettings.AppSettings["sothapphansaudaucach_SO"];
        private static string _SO_LUONG_THAP_PHAN_TIEN_USD = ConfigurationSettings.AppSettings["sothapphansaudaucach_TIEN_USD"];
        private static string _SO_LUONG_THAP_PHAN_TIEN_VND = ConfigurationSettings.AppSettings["sothapphansaudaucach_TIEN_VND"];

        // Methods
        public static bool CheckIfAlphabet(string salDesc)
        {
            Regex objAlphaPattern = new Regex(@"^\d+$");
            return objAlphaPattern.IsMatch(salDesc);
        }

        public static string FormatSo_CoThapPhan(double dblso)
        {
            string ReturnVal = "0";
            try
            {
                if (dblso.ToString() != "")
                {
                    string dinhdang = "{0:N" + _SO_LUONG_THAP_PHAN_SO + "}";
                    ReturnVal = string.Format(_CULTURE, dinhdang, new object[] { dblso });
                }
            }
            catch
            {
            }
            return ReturnVal;
        }

        public static string FormatSo_CoThapPhan(string strso)
        {
            string ReturnVal = "0";
            try
            {
                if (strso != "")
                {
                    string dinhdang = "{0:N" + _SO_LUONG_THAP_PHAN_SO + "}";
                    double dblSo = Convert.ToDouble(strso);
                    ReturnVal = string.Format(_CULTURE, dinhdang, new object[] { dblSo });
                }
            }
            catch
            {
            }
            return ReturnVal;
        }

        public static string FormatSo_KhongThapPhan(double dblso)
        {
            string ReturnVal = "0";
            try
            {
                if (dblso.ToString() != "")
                {
                    string dinhdang = "{0:N0}";
                    ReturnVal = string.Format(_CULTURE, dinhdang, new object[] { dblso });
                }
            }
            catch
            {
            }
            return ReturnVal;
        }

        public static string FormatSo_KhongThapPhan(string strso)
        {
            string ReturnVal = "0";
            try
            {
                if (strso != "")
                {
                    string dinhdang = "{0:N0}";
                    double dblSo = Convert.ToDouble(strso);
                    ReturnVal = string.Format(_CULTURE, dinhdang, new object[] { dblSo });
                }
            }
            catch
            {
            }
            return ReturnVal;
        }

        public static string FormatTien_USD(double dblsotienUSD)
        {
            string ReturnVal = "0";
            try
            {
                if (dblsotienUSD.ToString() != "")
                {
                    string dinhdang = "{0:N" + _SO_LUONG_THAP_PHAN_TIEN_USD + "}";
                    ReturnVal = string.Format(_CULTURE, dinhdang, new object[] { dblsotienUSD });
                }
            }
            catch
            {
            }
            return ReturnVal;
        }

        public static string FormatTien_USD(string strsotienUSD)
        {
            string ReturnVal = "0";
            try
            {
                if (strsotienUSD != "")
                {
                    string dinhdang = "{0:N" + _SO_LUONG_THAP_PHAN_TIEN_USD + "}";
                    double dboSoTienUSD = Convert.ToDouble(strsotienUSD);
                    ReturnVal = string.Format(_CULTURE, dinhdang, new object[] { dboSoTienUSD });
                }
            }
            catch
            {
            }
            return ReturnVal;
        }

        public static string FormatTien_VND(double dblsotien)
        {
            string ReturnVal = "0";
            try
            {
                if (dblsotien.ToString() != "")
                {
                    string dinhdang = "{0:N" + _SO_LUONG_THAP_PHAN_TIEN_VND + "}";
                    ReturnVal = string.Format(_CULTURE, dinhdang, new object[] { dblsotien });
                }
            }
            catch
            {
            }
            return ReturnVal;
        }

        public static string FormatTien_VND(string strsotien)
        {
            string ReturnVal = "0";
            try
            {
                if (strsotien != "")
                {
                    string dinhdang = "{0:N" + _SO_LUONG_THAP_PHAN_TIEN_VND + "}";
                    double dboSoTien = Convert.ToDouble(strsotien);
                    ReturnVal = string.Format(_CULTURE, dinhdang, new object[] { dboSoTien });
                }
            }
            catch
            {
            }
            return ReturnVal;
        }

        public static string HuyFormat(double dblso)
        {
            string ReturnVal = "0";
            try
            {
                if (dblso.ToString() != "")
                {
                    ReturnVal = dblso.ToString().Replace(_DAU_PHAN_NHOM, "");
                    ReturnVal = ReturnVal.Replace(_DAU_CACH_THAP_PHAN, ".");
                }
            }
            catch
            {
            }
            return ReturnVal;
        }

        public static string HuyFormat(string strso)
        {
            string ReturnVal = "";
            try
            {
                if (strso != "")
                {
                    ReturnVal = strso.Replace(_DAU_PHAN_NHOM, "");
                    ReturnVal = ReturnVal.Replace(_DAU_CACH_THAP_PHAN, ".");
                }
            }
            catch
            {
            }
            return ReturnVal;
        }

        // Properties
        private static CultureInfo CULTURE
        {
            get
            {
                return _CULTURE;
            }
            set
            {
                _CULTURE = value;
            }
        }

        private static string DAU_CACH_THAP_PHAN
        {
            get
            {
                return _DAU_CACH_THAP_PHAN;
            }
            set
            {
                _DAU_CACH_THAP_PHAN = value;
            }
        }

        private static string DAU_PHAN_NHOM
        {
            get
            {
                return _DAU_PHAN_NHOM;
            }
            set
            {
                _DAU_PHAN_NHOM = value;
            }
        }

        private static string SO_LUONG_THAP_PHAN_SO
        {
            get
            {
                return _SO_LUONG_THAP_PHAN_SO;
            }
            set
            {
                _SO_LUONG_THAP_PHAN_SO = value;
            }
        }

        private static string SO_LUONG_THAP_PHAN_TIEN_USD
        {
            get
            {
                return _SO_LUONG_THAP_PHAN_TIEN_USD;
            }
            set
            {
                _SO_LUONG_THAP_PHAN_TIEN_USD = value;
            }
        }

        private static string SO_LUONG_THAP_PHAN_TIEN_VND
        {
            get
            {
                return _SO_LUONG_THAP_PHAN_TIEN_VND;
            }
            set
            {
                _SO_LUONG_THAP_PHAN_TIEN_VND = value;
            }
        }

    }
    public class XuLy
    {
        // Methods
        public static bool CheckEmail(string stremail)
        {
            try
            {
                Regex regex = new Regex(@"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*");
                return regex.IsMatch(stremail);
            }
            catch
            {
                return false;
            }
        }

        public static int GetFileSize(string pathName)
        {
            int iVal = 0;
            try
            {
                FileInfo file = new FileInfo(pathName);
                if (file.Length > 0L)
                {
                    iVal = Convert.ToInt32((double)((file.Length / 0x400L) + 0.5));
                    if (iVal == 0)
                    {
                        iVal = 1;
                    }
                    return iVal;
                }
                return 0;
            }
            catch
            {
                return 0;
            }
        }

        public static string GetRandomPassword()
        {
            StringBuilder builder = new StringBuilder();
            builder.Append(RandomString(3, false));
            builder.Append(RandomNumber(100, 0x3e7));
            builder.Append(RandomString(2, false));
            return builder.ToString();
        }

        public static string GetRandomPassword(int numChar)
        {
            Random rd = new Random((int)DateTime.Now.Ticks);
            string key = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < numChar; i++)
            {
                sb.Append(key.Substring(rd.Next(0, key.Length - 1), 1));
            }
            return sb.ToString();
        }

        public static string GetRandomPassword(int numChars, int seed)
        {
            string[] chars = new string[] { 
            "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "P", "Q", 
            "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "2", "3", "4", "5", "6", "7", "8", 
            "9"
         };
            Random rnd = new Random(seed);
            string random = string.Empty;
            for (int i = 0; i < numChars; i++)
            {
                random = random + chars[rnd.Next(0, 0x21)];
            }
            return random;
        }

        public static string GetUniqueKey(int maxSize)
        {
            char[] chars = new char[0x3e];
            chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890".ToCharArray();
            int size = maxSize;
            byte[] data = new byte[1];
            RNGCryptoServiceProvider crypto = new RNGCryptoServiceProvider();
            crypto.GetNonZeroBytes(data);
            size = maxSize;
            data = new byte[size];
            crypto.GetNonZeroBytes(data);
            StringBuilder result = new StringBuilder(size);
            foreach (byte b in data)
            {
                result.Append(chars[b % (chars.Length - 1)]);
            }
            return (DateTime.Now.ToString("yyyyMMdd") + result.ToString());
        }

        private static int RandomNumber(int min, int max)
        {
            Random random = new Random();
            return random.Next(min, max);
        }

        private static string RandomString(int size, bool lowerCase)
        {
            StringBuilder builder = new StringBuilder();
            Random random = new Random();
            for (int i = 0; i < size; i++)
            {
                char ch = Convert.ToChar(Convert.ToInt32(Math.Floor((double)((26.0 * random.NextDouble()) + 65.0))));
                builder.Append(ch);
            }
            if (lowerCase)
            {
                return builder.ToString().ToLower();
            }
            return builder.ToString();
        }

        public static DataSet ReadXML(string path, string XmlName)
        {
            DataSet ds = new DataSet();
            try
            {
                string xmlFile = path + XmlName;
                if (File.Exists(xmlFile))
                {
                    FileStream fstr = new FileStream(xmlFile, FileMode.Open, FileAccess.Read);
                    ds.ReadXml(fstr);
                    fstr.Close();
                }
            }
            catch
            {
                ds = null;
            }
            return ds;
        }

    }
    public class XuLyUpDown
    {
        // Fields
        private static string[] arrFileExtension = ConfigurationSettings.AppSettings["FileExts"].Split(new char[] { '|' });
        private static string[] arrImageExtension = ConfigurationSettings.AppSettings["ImgExts"].Split(new char[] { '|' });
        private static long maxSizeFile = Convert.ToInt64(string.IsNullOrEmpty(ConfigurationSettings.AppSettings["maxSizeFile"].ToString()) ? "100000" : ConfigurationSettings.AppSettings["maxSizeFile"].ToString());
        private static long maxSizeImg = Convert.ToInt64(string.IsNullOrEmpty(ConfigurationSettings.AppSettings["maxSizeImg"].ToString()) ? "100000" : ConfigurationSettings.AppSettings["maxSizeImg"].ToString());

        // Methods
        private static bool CheckExistsExts(string[] arrStr, string strExts)
        {
            for (int i = 0; i < arrStr.Length; i++)
            {
                if (arrStr[i].ToString() == strExts)
                {
                    return true;
                }
            }
            return false;
        }

        private static bool CheckFileExists(string strFullPath)
        {
            bool flag = false;
            try
            {
                FileInfo fileInfo = new FileInfo(strFullPath);
                if (fileInfo.Exists)
                {
                    flag = true;
                }
            }
            catch
            {
                flag = false;
            }
            return flag;
        }

        public static bool DeleteFile(string path)
        {
            bool flag = false;
            try
            {
                FileInfo fileInfo = new FileInfo(path);
                if (fileInfo.Exists)
                {
                    fileInfo.Delete();
                    flag = true;
                }
            }
            catch
            {
                flag = false;
            }
            return flag;
        }

        public static void DownloadFile(string filePath)
        {
            try
            {
                HttpContext.Current.Response.ContentType = "application/octet-stream";
                HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + Path.GetFileName(filePath));
                HttpContext.Current.Response.Clear();
                HttpContext.Current.Response.WriteFile(filePath);
                HttpContext.Current.Response.End();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public static bool DownloadFileFTP(string strPath, string strpathsave, string username, string pass)
        {
            try
            {
                WebClient request = new WebClient();
                request.Credentials = new NetworkCredential(username, pass);
                byte[] filedata = request.DownloadData(strPath);
                FileStream file = File.Create(strpathsave);
                file.Write(filedata, 0, filedata.Length);
                file.Close();
                return true;
            }
            catch
            {
                return false;
            }
        }

        public static string GetFileExtension(string filePath)
        {
            FileInfo fi = new FileInfo(filePath);
            return fi.Extension;
        }

        public static string GetFileName(string filePath)
        {
            FileInfo fi = new FileInfo(filePath);
            return fi.Name;
        }

        public static int GetFileSize(string pathName)
        {
            int iVal = 0;
            try
            {
                FileInfo file = new FileInfo(pathName);
                if (file.Length > 0L)
                {
                    iVal = Convert.ToInt32((double)((file.Length / 0x400L) + 0.5));
                    if (iVal == 0)
                    {
                        iVal = 1;
                    }
                    return iVal;
                }
                return 0;
            }
            catch
            {
                return 0;
            }
        }

        public static int GetFileSize(FileUpload inputFile)
        {
            int KichThuoc = 0;
            if (inputFile.HasFile && (inputFile.PostedFile != null))
            {
                KichThuoc = inputFile.PostedFile.ContentLength;
            }
            return KichThuoc;
        }

        private static bool ThumbnailCallback()
        {
            return false;
        }

        public static string UploadFiles(FileUpload inputFile, string strPath)
        {
            string strFileName = string.Empty;
            try
            {
                if (inputFile.HasFile)
                {
                    if (inputFile.PostedFile.ContentLength > maxSizeFile)
                    {
                        return "1";
                    }
                    string filename = inputFile.FileName;
                    string strExt = filename.Substring(filename.LastIndexOf('.') + 1).ToLower();
                    if (CheckExistsExts(arrFileExtension, strExt))
                    {
                        strFileName = (DateTime.Now.ToString("yyyyMMddhhmmss") + "_" + XuLyChuoi.RejectMarks(filename.Substring(0, (filename.Length - strExt.Length) - 1))).Replace(" ", "");
                        strFileName = strFileName.Substring(0, (strFileName.Length > 200) ? 200 : strFileName.Length) + "." + strExt;
                        if (!CheckFileExists(strPath + strFileName))
                        {
                            inputFile.SaveAs(strPath + strFileName);
                        }
                        return strFileName;
                    }
                    return "2";
                }
                return string.Empty;
            }
            catch
            {
                return string.Empty;
            }
        }

        public static string UploadFilesFTP(string strFileUpload, string strPath, string username, string pass)
        {
            string strFileName = string.Empty;
            try
            {
                FileInfo toUpload = new FileInfo(strFileUpload);
                strFileName = DateTime.Now.ToString("yyyyMMddhhmmss") + "_" + toUpload.Name;
                FtpWebRequest request = (FtpWebRequest)WebRequest.Create(strPath + "/" + strFileName);
                request.Method = "STOR";
                request.Credentials = new NetworkCredential(username, pass);
                Stream ftpStream = request.GetRequestStream();
                FileStream file = File.OpenRead(strFileUpload);
                int length = 0x400;
                byte[] buffer = new byte[length];
                int byteread = 0;
                do
                {
                    byteread = file.Read(buffer, 0, length);
                    ftpStream.Write(buffer, 0, byteread);
                }
                while (byteread != 0);
                file.Close();
                ftpStream.Close();
            }
            catch
            {
                strFileName = string.Empty;
            }
            return strFileName;
        }

        public static string UploadImages(FileUpload inputFile, string strPath)
        {
            string strFileName = string.Empty;
            try
            {
                if (inputFile.HasFile)
                {
                    if (inputFile.PostedFile.ContentLength > maxSizeImg)
                    {
                        return "1";
                    }
                    string filename = inputFile.FileName;
                    string strExt = filename.Substring(filename.LastIndexOf('.') + 1).ToLower();
                    if (!CheckExistsExts(arrImageExtension, strExt))
                    {
                        return filename;
                    }
                    strFileName = (DateTime.Now.ToString("yyyyMMddhhmmss") + "_" + XuLyChuoi.RejectMarks(filename.Substring(0, (filename.Length - strExt.Length) - 1))).Replace(" ", "");
                    strFileName = strFileName.Substring(0, (strFileName.Length > 200) ? 200 : strFileName.Length) + "." + strExt;
                    if (!CheckFileExists(strPath + strFileName))
                    {
                        inputFile.SaveAs(strPath + strFileName);
                    }
                    return strFileName;
                }
                return string.Empty;
            }
            catch
            {
                return string.Empty;
            }
        }

        public static string UploadImages(FileUpload inputFile, string strPath, int imageHeight, int imageWidth)
        {
            string strFileName = string.Empty;
            try
            {
                if (inputFile.HasFile)
                {
                    if (inputFile.PostedFile.ContentLength > maxSizeImg)
                    {
                        return "1";
                    }
                    string filename = inputFile.FileName;
                    string strExt = filename.Substring(filename.LastIndexOf('.') + 1).ToLower();
                    if (CheckExistsExts(arrImageExtension, strExt))
                    {
                        strFileName = (DateTime.Now.ToString("yyyyMMddhhmmss") + "_" + XuLyChuoi.RejectMarks(filename.Substring(0, (filename.Length - strExt.Length) - 1))).Replace(" ", "");
                        strFileName = strFileName.Substring(0, (strFileName.Length > 200) ? 200 : strFileName.Length) + "." + strExt;
                        if (!CheckFileExists(strPath + strFileName))
                        {
                            inputFile.PostedFile.SaveAs(strPath + strFileName);
                            try
                            {
                                System.Drawing.Image fullSizeImg = System.Drawing.Image.FromFile(strPath + strFileName);
                                System.Drawing.Image.GetThumbnailImageAbort dummyCallBack = new System.Drawing.Image.GetThumbnailImageAbort(XuLyUpDown.ThumbnailCallback);
                                System.Drawing.Image thumbNailImg = fullSizeImg.GetThumbnailImage(imageWidth, imageHeight, dummyCallBack, IntPtr.Zero);
                                thumbNailImg.Save(strPath + (strFileName + "_thumb.jpg"), ImageFormat.Jpeg);
                                thumbNailImg.Dispose();
                            }
                            catch
                            {
                            }
                        }
                        return strFileName;
                    }
                    return "2";
                }
                return string.Empty;
            }
            catch
            {
                return string.Empty;
            }
        }

    }
    public class XulyNgay
    {
        // Methods
        public static string ConvertDateTimeToString(DateTime date)
        {
            MyDate mydate = new MyDate(date);
            return mydate.ToString();
        }

        public static DateTime ConvertStringToDateTime(string str)
        {
            MyDate mydate = new MyDate(str);
            return mydate.ToDateTime();
        }

        public static string FuncDateChange(string str)
        {
            try
            {
                string[] sp = str.Split(new char[] { '/' });
                return (sp[1] + "/" + sp[0] + "/" + sp[2]);
            }
            catch
            {
                return "01/01/1900";
            }
        }

        public static bool KiemTraNgayThang(string NgayThangNam)
        {
            try
            {
                int intNgay;
                int intThang;
                int intNam;
                if (NgayThangNam.ToString() == "")
                {
                    return false;
                }
                string[] arr = NgayThangNam.Split(new char[] { '/' });
                if (arr.Length != 3)
                {
                    return false;
                }
                string Ngay = arr[0].ToString();
                string Thang = arr[1].ToString();
                string Nam = arr[2].ToString();
                try
                {
                    intNgay = Convert.ToInt32(Ngay);
                    intThang = Convert.ToInt32(Thang);
                    intNam = Convert.ToInt32(Nam);
                }
                catch
                {
                    return false;
                }
                if (intNam < 0x76c)
                {
                    return false;
                }
                if ((intThang < 1) || (intThang > 12))
                {
                    return false;
                }
                if ((intNgay < 1) || (intNgay > 0x1f))
                {
                    return false;
                }
                if ((((((intThang == 1) || (intThang == 3)) || ((intThang == 5) || (intThang == 7))) || ((intThang == 8) || (intThang == 10))) || (intThang == 12)) && ((intNgay < 1) || (intNgay > 0x1f)))
                {
                    return false;
                }
                if (((((intThang == 4) || (intThang == 6)) || (intThang == 9)) || (intThang == 11)) && ((intNgay < 1) || (intNgay > 30)))
                {
                    return false;
                }
                if ((((intNam % 4) == 0) && ((intNam % 100) != 0)) || ((intNam % 400) == 0))
                {
                    if ((intThang == 2) && (intNgay > 0x1c))
                    {
                        return false;
                    }
                }
                else if ((intThang == 2) && (intNgay > 0x1d))
                {
                    return false;
                }
            }
            catch
            {
                return false;
            }
            return true;
        }

    }
    public class SendMail
    {
        // Fields
        private string _attachmentPath;
        private string _body;
        private string _fromPWD;
        private string _hostName;
        private string _sendBCC;
        private string _sendFrom;
        private string _sendFromName;
        private string _sendTo;
        private string _subject;

        // Methods
        public SendMail()
        {
            this.SendFrom = "";
            this.SendTo = "";
            this.SendBCC = "";
            this.Subject = "";
            this.Body = "";
            this.AttachmentPath = "";
            this.HostName = "smtp.gmail.com";
            this.FromPWD = "";
        }

        public bool Send_Email()
        {
            bool rVal = false;
            try
            {
                Regex regex = new Regex(@"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*");
                bool result = true;
                string[] ALL_EMAILS = this.SendTo.Split(new char[] { ';' });
                foreach (string emailaddress in ALL_EMAILS)
                {
                    result = regex.IsMatch(emailaddress);
                    if (!result)
                    {
                        return false;
                    }
                }
                if (result)
                {
                    SmtpClient smtp = new SmtpClient();
                    MailMessage msg = new MailMessage();
                    msg.From = new MailAddress(this.SendFrom, this.SendFromName);
                    foreach (string emailaddress in ALL_EMAILS)
                    {
                        msg.To.Add(new MailAddress(emailaddress));
                    }
                    msg.Subject = this.Subject;
                    msg.Body = this.Body;
                    msg.IsBodyHtml = true;
                    if (this.AttachmentPath != "")
                    {
                        Attachment attach = new Attachment(this.AttachmentPath);
                        msg.Attachments.Add(attach);
                    }
                    msg.Priority = MailPriority.High;
                    if (this.HostName != "")
                    {
                        smtp.Host = this.HostName;
                    }
                    smtp.EnableSsl = false;
                    smtp.UseDefaultCredentials = false;
                    smtp.DeliveryMethod = SmtpDeliveryMethod.PickupDirectoryFromIis;
                    smtp.Send(msg);
                    rVal = true;
                }
            }
            catch (Exception)
            {
                rVal = false;
            }
            return rVal;
        }

        public bool Send_EmailPW()
        {
            bool rVal = false;
            try
            {
                Regex regex = new Regex(@"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*");
                bool result = true;
                string[] ALL_EMAILS = this.SendTo.Split(new char[] { ';' });
                foreach (string emailaddress in ALL_EMAILS)
                {
                    result = regex.IsMatch(emailaddress);
                    if (!result)
                    {
                        return false;
                    }
                }
                if (result)
                {
                    NetworkCredential loginInfo = new NetworkCredential(this.SendFrom, this.FromPWD);
                    SmtpClient smtp = new SmtpClient();
                    MailMessage msg = new MailMessage();
                    msg.From = new MailAddress(this.SendFrom, this.SendFromName);
                    foreach (string emailaddress in ALL_EMAILS)
                    {
                        msg.To.Add(new MailAddress(emailaddress));
                    }
                    msg.Subject = this.Subject;
                    msg.Body = this.Body;
                    msg.IsBodyHtml = true;
                    if (this.AttachmentPath != "")
                    {
                        Attachment attach = new Attachment(this.AttachmentPath);
                        msg.Attachments.Add(attach);
                    }
                    msg.Priority = MailPriority.High;
                    if (this.HostName != "")
                    {
                        smtp.Host = this.HostName;
                    }
                    smtp.EnableSsl = false;
                    smtp.UseDefaultCredentials = false;
                    smtp.Credentials = loginInfo;
                    smtp.Send(msg);
                    rVal = true;
                }
            }
            catch (Exception)
            {
                rVal = false;
            }
            return rVal;
        }

        // Properties
        public string AttachmentPath
        {
            get
            {
                return this._attachmentPath;
            }
            set
            {
                this._attachmentPath = value;
            }
        }
        public string Body
        {
            get
            {
                return this._body;
            }
            set
            {
                this._body = value;
            }
        }
        public string FromPWD
        {
            get
            {
                return this._fromPWD;
            }
            set
            {
                this._fromPWD = value;
            }
        }
        public string HostName
        {
            get
            {
                return this._hostName;
            }
            set
            {
                this._hostName = value;
            }
        }
        public string SendBCC
        {
            get
            {
                return this._sendBCC;
            }
            set
            {
                this._sendBCC = value;
            }
        }
        public string SendFrom
        {
            get
            {
                return this._sendFrom;
            }
            set
            {
                this._sendFrom = value;
            }
        }
        public string SendFromName
        {
            get
            {
                return this._sendFromName;
            }
            set
            {
                this._sendFromName = value;
            }
        }
        public string SendTo
        {
            get
            {
                return this._sendTo;
            }
            set
            {
                this._sendTo = value;
            }
        }

        public string Subject
        {
            get
            {
                return this._subject;
            }
            set
            {
                this._subject = value;
            }
        }

    }
    public static class IsNumeric
    {
        // Methods
        public static bool IsInteger(string strNumber)
        {
            Regex objNotIntPattern = new Regex("[^0-9-]");
            Regex objIntPattern = new Regex("^-[0-9]+$|^[0-9]+$");
            return (!objNotIntPattern.IsMatch(strNumber) && objIntPattern.IsMatch(strNumber));
        }

        public static bool IsNaturalNumber(string strNumber)
        {
            Regex objNotNaturalPattern = new Regex("[^0-9]");
            Regex objNaturalPattern = new Regex("0*[1-9][0-9]*");
            return (!objNotNaturalPattern.IsMatch(strNumber) && objNaturalPattern.IsMatch(strNumber));
        }

        public static bool IsNumber(string strNumber)
        {
            Regex objNotNumberPattern = new Regex("[^0-9.-]");
            Regex objTwoDotPattern = new Regex("[0-9]*[.][0-9]*[.][0-9]*");
            Regex objTwoMinusPattern = new Regex("[0-9]*[-][0-9]*[-][0-9]*");
            string strValidRealPattern = "^([-]|[.]|[-.]|[0-9])[0-9]*[.]*[0-9]+$";
            string strValidIntegerPattern = "^([-]|[0-9])[0-9]*$";
            Regex objNumberPattern = new Regex("(" + strValidRealPattern + ")|(" + strValidIntegerPattern + ")");
            return (((!objNotNumberPattern.IsMatch(strNumber) && !objTwoDotPattern.IsMatch(strNumber)) && !objTwoMinusPattern.IsMatch(strNumber)) && objNumberPattern.IsMatch(strNumber));
        }

        public static bool IsPositiveNumber(string strNumber)
        {
            Regex objNotPositivePattern = new Regex("[^0-9.]");
            Regex objPositivePattern = new Regex("^[.][0-9]+$|[0-9]*[.]*[0-9]+$");
            Regex objTwoDotPattern = new Regex("[0-9]*[.][0-9]*[.][0-9]*");
            return ((!objNotPositivePattern.IsMatch(strNumber) && objPositivePattern.IsMatch(strNumber)) && !objTwoDotPattern.IsMatch(strNumber));
        }

        public static bool IsWholeNumber(string strNumber)
        {
            Regex objNotWholePattern = new Regex("[^0-9]");
            return !objNotWholePattern.IsMatch(strNumber);
        }

    }
    public class XuLyChuoi
    {
        // Methods
        public static string CutString(string Chuoi, int Sotu)
        {
            string str = "";
            try
            {
                if (Chuoi.Length <= 0)
                {
                    return str;
                }
                string[] arrChuoi = Chuoi.Split(new char[] { ' ' });
                int len = arrChuoi.Length;
                if (Sotu >= len)
                {
                    return Chuoi;
                }
                for (int i = 0; i < Sotu; i++)
                {
                    str = str + arrChuoi[i].ToString() + " ";
                }
                return (str + "...");
            }
            catch
            {
                return Chuoi;
            }
        }

        public static string FormatNumber(double Num)
        {
            string rval = Num.ToString();
            try
            {
                if (IsNumeric.IsPositiveNumber(Num.ToString()))
                {
                    rval = string.Format("{0:#,0.##}", Num);
                }
            }
            catch
            {
                rval = "0";
            }
            return rval;
        }

        public static string Insert(string input, string value, int startIndex, bool rightToLeft)
        {
            if (rightToLeft)
            {
                if (startIndex > input.Length)
                {
                    startIndex = 0;
                }
                else
                {
                    startIndex = input.Length - startIndex;
                }
            }
            else if (startIndex > input.Length)
            {
                startIndex = input.Length;
            }
            return input.Insert(startIndex, value);
        }

        public static bool IsAlpha(string strToCheck)
        {
            Regex objAlphaPattern = new Regex("[^a-zA-Z]");
            return !objAlphaPattern.IsMatch(strToCheck);
        }

        public static bool IsAlphaNumeric(string strToCheck)
        {
            Regex objAlphaNumericPattern = new Regex("[^a-zA-Z0-9]");
            return !objAlphaNumericPattern.IsMatch(strToCheck);
        }

        public static string RejectMarks(string text)
        {
            string[] pattern = new string[] { "a|(\x00e1|ả|\x00e0|ạ|\x00e3|ă|ắ|ẳ|ằ|ặ|ẵ|\x00e2|ấ|ẩ|ầ|ậ|ẫ)", "o|(\x00f3|ỏ|\x00f2|ọ|\x00f5|\x00f4|ố|ổ|ồ|ộ|ỗ|ơ|ớ|ở|ờ|ợ|ỡ)", "e|(\x00e9|\x00e8|ẻ|ẹ|ẽ|\x00ea|ế|ề|ể|ệ|ễ)", "u|(\x00fa|\x00f9|ủ|ụ|ũ|ư|ứ|ừ|ử|ự|ữ)", "i|(\x00ed|\x00ec|ỉ|ị|ĩ)", "y|(\x00fd|ỳ|ỷ|ỵ|ỹ)", "d|đ" };
            for (int i = 0; i < pattern.Length; i++)
            {
                char replaceChar = pattern[i][0];
                MatchCollection matchs = Regex.Matches(text, pattern[i]);
                foreach (Match m in matchs)
                {
                    text = text.Replace(m.Value[0], replaceChar);
                }
            }
            return text;
        }

        public static string Remove(string input, int startIndex, int count, bool rightToLeft)
        {
            string str = "";
            try
            {
                if (rightToLeft)
                {
                    if (startIndex > input.Length)
                    {
                        startIndex = 0;
                    }
                    else
                    {
                        startIndex = (input.Length - startIndex) - count;
                    }
                }
                else if (startIndex > input.Length)
                {
                    startIndex = input.Length;
                }
                startIndex = (startIndex < 0) ? 0 : startIndex;
                if (count > input.Length)
                {
                    count = input.Length;
                }
                else
                {
                    count = (count < 0) ? 0 : count;
                }
                str = input.Remove(startIndex, count);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return str;
        }

        public static string Replace(string input, string oldValue, string newValue, bool matchCase)
        {
            RegexOptions regexOption = RegexOptions.None;
            if (!matchCase)
            {
                regexOption = RegexOptions.IgnoreCase;
            }
            input = new Regex(oldValue, regexOption).Replace(input, newValue);
            return input;
        }

        public static string TimKiem(DataView dv, string strKey, string TenCot)
        {
            string chuoi = "";
            try
            {
                if (strKey.IndexOf("'") >= 0)
                {
                    strKey = strKey.Replace("'", "");
                }
                if (TenCot.IndexOf("'") >= 0)
                {
                    TenCot = TenCot.Replace("'", "");
                }
                switch (dv.Table.Columns[TenCot].DataType.ToString())
                {
                    case "System.DateTime":
                        if (XulyNgay.KiemTraNgayThang(strKey))
                        {
                            return (TenCot = TenCot + " like '" + strKey + "'");
                        }
                        return (TenCot = TenCot + " like '1/1/1'");

                    case "System.String":
                        return (TenCot = TenCot + " like '%" + strKey + "%'");

                    case "System.Int32":
                        return (TenCot = TenCot + " = " + Convert.ToInt32(strKey));

                    case "System.Int64":
                        return (TenCot = TenCot + " = " + Convert.ToInt64(strKey));
                }
                chuoi = TenCot = TenCot + " like '%" + strKey + "%'";
            }
            catch
            {
            }
            return chuoi;
        }

        public static string ToTitleCase(string str)
        {
            str = str.ToLower();
            char[] charArr = str.ToCharArray();
            charArr[0] = char.ToUpper(charArr[0]);
            foreach (Match m in Regex.Matches(str, @"(\s\S)"))
            {
                charArr[m.Index + 1] = m.Value.ToUpper().Trim()[0];
            }
            return new string(charArr);
        }

        public static string ToToggleCase(string str)
        {
            string ret = "";
            foreach (char c in str)
            {
                string s = c.ToString();
                if (s == s.ToLower())
                {
                    ret = ret + s.ToUpper();
                }
                else
                {
                    ret = ret + s.ToLower();
                }
            }
            return ret;
        }

    }
}

   